﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Taxonomy.WebServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Threading.Tasks;

namespace MMNavigation
{
    [ServiceContract(Namespace = "TaxonomyFieldValues")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class TaxonomyFieldValues
    {
        [OperationContract(Action="GetTaxonomyFieldValues")]
        List<TaxonomyFieldValue> GetFieldValues(string ListAbsoluteUrl, string FieldName)
        {
            using (SPSite sitecollection = new SPSite(ListAbsoluteUrl))
            {
                using (SPWeb site = sitecollection.OpenWeb())
                {
                    SPList list = site.GetList((new Uri(ListAbsoluteUrl).PathAndQuery));
                    return GetFieldValues(list.Fields.GetField(FieldName) as TaxonomyField);
                }
            }
        }

        List<TaxonomyFieldValue> GetFieldValues(TaxonomyField tField)
        {
            TaxonomySession taxSession = new TaxonomySession(tField.ParentList.ParentWeb.Site);
            //TODO: i had to use the ParentList here, which means a List Field, is it possible to use just a Site Column here?
            TermSet termSet = taxSession.TermStores.SelectMany<TermStore, TermSet>(_ => new List<TermSet> { _.GetTermSet(tField.TermSetId) }).FirstOrDefault();
            Term anchor = termSet.GetTerm(tField.AnchorId);
            return termSet.GetAllTerms().Where(_ => _.GetIsDescendantOf(anchor) && _.IsAvailableForTagging && !_.IsDeprecated).Select(_ => new TaxonomyFieldValue() { Path = _.GetPath(), Label = _.GetDefaultLabel((int)(tField.ParentList.ParentWeb.Language)), ID = _.Id.ToString() }).ToList();
        }
    }

    [DataContract]
    public class TaxonomyFieldValue
    {
        [DataMember]
        public string Path;
        [DataMember]
        public string Label;
        [DataMember]
        public string ID;
    }

}
